#!/usr/bin/python
import sys
import subprocess
import os

nachos_path = "../userprog/nachos"

#these are programs that shouldn't be run on their own, because they
#are a part of a different program's test.
bad_tests = ["signal_child"]

"""
Executes a program with nachos. Program must be a program that was converted 
with coff2noff
"""
def test(fname, debug):
    if "shell" in fname: return

    print "\n\nTESTING {0}".format(fname) + "-"*50
    print "../userprog/nachos -d {0} -x ../test/{1}".format(debug,fname)
    ret = subprocess.call("{0} -d {1} -x ../test/{2}".format(nachos_path, debug,fname), shell=True)


"""
Converts programs compiled with make to nachos standard with coff2noff, then
runs each program that was converted.
"""
def tests(test_executables, debug = "at"):

    print "\n\nBEGIN TESTS" + "-" * 50
    for t in test_executables:
        test(t, debug)


usage = """
Usage:
    running nachos_test with no arguments cleans up, then compiles everything,
    and finally runs all the programs that are available for testing

    if nachos_test was run with arguments, then test each file that was given
    to be tested. The files given are assumed to be binaries to tests that 
    haven't yet been converted with coff2noff
"""
def main():
    debug_flags = "ft"
    if "-d" in sys.argv:
        ind = sys.argv.index("-d")
        if ind < len(sys.argv) - 1:
            debug_flags = sys.argv[ind + 1]

        print sys.argv
        sys.argv.pop(ind)
        sys.argv.pop(ind)

    if len(sys.argv) == 1: #no more flags so just test all executables
        test_executables = None
        with open("Makefile") as f:
            for l in f:
                if l.startswith("EXE"):
                    test_executables = l.split()[2:]

        tests(test_executables, debug_flags)
    else: #args left, so assume that they are all executaibles to run
        for bad_test in bad_tests:
            if bad_test in sys.argv:
                print "Removing bad test: {0}".format(bad_test)
                sys.argv.remove(bad_test)
        fnames = sys.argv[1:]
        tests(fnames, debug_flags)

if __name__=="__main__":
    main()
